//
//  InfoView.m
//  PotentialTraining
//
//  Created by admin on 2018/2/2.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "InfoView.h"
#import "VipInfoCell.h"
#import "BRTextField.h"
#import "PTAddressView.h"
@interface InfoView ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate,UIGestureRecognizerDelegate,DidSelecteAddress>

@property (nonatomic, strong) UITableView *infoTab;

@property (nonatomic, strong) UILabel *tishiLabel;
/** 姓名 */
@property (nonatomic, strong) BRTextField *nameTF;
/** 年龄 */
@property (nonatomic, strong) BRTextField *ageTF;
/** 签名 */
@property (nonatomic, strong) BRTextField *qainTF;
/** 地区 */
@property (nonatomic, strong) BRTextField *addressTF;
/** 确定修改按钮 */
@property (nonatomic, strong) UIButton *sendBtn;
@property (nonatomic, strong) NSArray *tagAry;
/** 登陆View */
@property (nonatomic, strong) UIView *loginView;
/** 登陆按钮 */
@property (nonatomic, strong) UIButton *loginBtn;

@property (nonatomic, strong) NSDictionary *userDic;

@property (nonatomic, copy) NSString *proName;

@property (nonatomic, copy) NSString *cityName;

@property (nonatomic, copy) NSString *countyName;

@end
@implementation InfoView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        [self addSubview:self.infoTab];
//        [self addSubview:self.loginView];
        [self.loginView addSubview:self.loginBtn];
        
        self.userDic = [NSDictionary dictionary];
    }
    return self;
}


- (void) touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {

    for (UITouch *touchGes in touches) {
        
        if ([touchGes.view isEqual:self]) {
            
            [self hideAddressView];
        } else {
            [self endEditing:YES];
        }
    }
}

- (UITableView *)infoTab{
    if (_infoTab == nil) {
        _infoTab = [[UITableView alloc]initWithFrame:CGRectMake(60, 60, kScreenWidth - 300-120, kScreenHeight - 49-64-120)];
        _infoTab.backgroundColor = [UIColor whiteColor];
        _infoTab.delegate = self;
        _infoTab.dataSource = self;
        _infoTab.scrollEnabled = NO;
        _infoTab.separatorStyle = UITableViewCellSeparatorStyleNone;
        _infoTab.tableFooterView = [UIView new];
        [_infoTab registerNib:[UINib nibWithNibName:NSStringFromClass([VipInfoCell class]) bundle:nil] forCellReuseIdentifier:@"VipInfoCell"];
    }
    return _infoTab;
}
#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VipInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"VipInfoCell"];
    cell.tagLabel.text = self.tagAry[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
        case 0:
        {
            [self setupNameTF:cell];
        }
            break;
        case 1:
        {
            [self setupAgeTF:cell];
        }
            break;
        case 2:
        {
            [self setupQianTF:cell];
        }
            break;
        case 3:
        {
            [self setupAddressTF:cell];
        }
            break;
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 300-120, 200)];
    [view addSubview:self.headImg];
    [view addSubview:self.tishiLabel];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headTap)];
    [view addGestureRecognizer:tap];
    
    return view;
}
- (void) headTap {
    
    [self hideAddressView];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 200;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth - 300-120, 70)];
    [view addSubview:self.sendBtn];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 70;
}

#pragma mark - 点击上传头像
- (void) tapCovreView:(UIImageView *)headView{
    NSLog(@"点击了头像");
    if ([self.HeadImgDetegate respondsToSelector:@selector(DidselectTHeadImg:)]){
        [self.HeadImgDetegate DidselectTHeadImg:headView];
    }
}

#pragma mark - 保存
- (void)clickSendInfoButton{
     NSDictionary *userInfoDic = [NSDictionary dictionaryWithContentsOfFile:kInfoFilePath];
    NSString *name = self.nameTF.text;
    if (name.length <= 0) {
        name = userInfoDic[@"username"];
    }
    NSString *age = self.ageTF.text;
    if (age.length <= 0) {
        age = userInfoDic[@"age"];
    }
    NSString *info = self.qainTF.text;
    if (info.length <= 0) {
        info = userInfoDic[@"sign"];
    }
    NSString *address = self.addressTF.text;
    if (address.length <= 0) {
        address = userInfoDic[@"city_id"];
    }
    [self endEditing:YES];
    if ([self.HeadImgDetegate respondsToSelector:@selector(didClickSendInfoButton:)]){
        [self.HeadImgDetegate didClickSendInfoButton:@{
                                                       @"name":name,
                                                       @"age":age,
                                                       @"info":info,
                                                       @"address":address
                                                       }];
    }
}

- (UIImageView *)headImg{
    if (_headImg == nil) {
        _headImg = [[UIImageView alloc]init];
        _headImg.frame = CGRectMake((kScreenWidth - 300-120)/2-60, 20, 120, 120);
        _headImg.contentMode = UIViewContentModeScaleAspectFill;
        _headImg.clipsToBounds = YES;
        _headImg.layer.cornerRadius = 60;
        _headImg.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapCovreView:)];
        tap.delegate = self;
        [_headImg addGestureRecognizer:tap];
    }
    return _headImg;
}

- (UILabel *)tishiLabel{
    if (_tishiLabel == nil) {
        _tishiLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 140, kScreenWidth - 300-120, 60)];
        _tishiLabel.textAlignment = NSTextAlignmentCenter;
        _tishiLabel.font = [UIFont systemFontOfSize:20];
        _tishiLabel.textColor = [UIColor grayColor];
        _tishiLabel.text = @"点击上传修改头像";
    }
    return _tishiLabel;
}
#pragma mark - 设置textfield
- (BRTextField *)getTextField:(UITableViewCell *)cell {
    BRTextField *textField = [[BRTextField alloc]initWithFrame:CGRectMake(75, 0, kScreenWidth - 300-120-60-30, 60)];
    textField.backgroundColor = [UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:18.0f];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor = [UIColor blackColor];
    textField.delegate = self;
    [cell.contentView addSubview:textField];
    return textField;
}

#pragma mark - 姓名 textField
- (void)setupNameTF:(UITableViewCell *)cell {
    if (!_nameTF) {
        _nameTF = [self getTextField:cell];
        _nameTF.placeholder = self.dataDic[@"username"] ?: @"";
        _nameTF.returnKeyType = UIReturnKeyDone;
        _nameTF.tag = 0;
    }
}
#pragma mark - 年龄 textField
- (void)setupAgeTF:(UITableViewCell *)cell {
    if (!_ageTF) {
        _ageTF = [self getTextField:cell];
        _ageTF.placeholder = self.dataDic[@"age"] ?: @"";
        _ageTF.returnKeyType = UIReturnKeyDone;
        _ageTF.tag = 0;
    }
}
#pragma mark - 签名 textField
- (void)setupQianTF:(UITableViewCell *)cell {
    if (!_qainTF) {
        _qainTF = [self getTextField:cell];
        _qainTF.placeholder = self.dataDic[@"sign"] ?: @"";
        _qainTF.returnKeyType = UIReturnKeyDone;
        _qainTF.tag = 0;
    }
}

#pragma mark - 地区 textField
- (void)setupAddressTF:(UITableViewCell *)cell {
    if (!_addressTF) {
        _addressTF = [self getTextField:cell];
        _addressTF.placeholder = self.dataDic[@"name"];
//        [_addressTF addTarget:self action:@selector(addressTFEdidtig:) forControlEvents:UIControlEventAllEvents];
        _addressTF.returnKeyType = UIReturnKeyDone;
        _addressTF.tag = 0;
    }
}

- (BOOL) textFieldShouldBeginEditing:(UITextField *)textField {
    
    if ([textField isEqual:_addressTF]) {
        
        [self endEditing:YES];
        
        
//        if (self.addressView == nil) {
        
            self.addressView = [[PTAddressView alloc] initWithFrame:CGRectMake(0, self.frame.size.height, kScreenWidth, 500)];
        self.addressView.AddressDelegate = self;
            [self addSubview:self.addressView];
//        }
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self.addressView.frame = CGRectMake(0, self.frame.size.height - 500, kScreenWidth, 500);
        }];
        
        
        return NO;
    }
    
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.addressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 500);
    }];
    return YES;
}

- (void) selecteAddress:(NSArray *)addressArr {
    
    if ([self.HeadImgDetegate respondsToSelector:@selector(didSelectedAddress:)]) {
        
        
        NSDictionary *proDic = addressArr[0];
        NSDictionary *cityDic = addressArr[1];
        NSDictionary *countyDic = addressArr[2];
        _addressTF.text = [NSString stringWithFormat:@"%@%@%@", proDic[@"name"], cityDic[@"name"], countyDic[@"name"]];
        
        [self.HeadImgDetegate didSelectedAddress:addressArr];
    }
    
}


- (UIButton  *)sendBtn{
    if (_sendBtn == nil) {
        _sendBtn = [UIButton buttonWithType:0];
        [_sendBtn setTitle:@"保存信息" forState:UIControlStateNormal];
        _sendBtn.backgroundColor = [UIColor blueColor];
        [_sendBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _sendBtn.clipsToBounds = YES;
        _sendBtn.layer.cornerRadius = 5;
        _sendBtn.frame = CGRectMake((kScreenWidth - 300-120)/2-75, 20, 150, 50);
        [_sendBtn addTarget:self action:@selector(clickSendInfoButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _sendBtn;
}

- (UIView *)loginView {
    if (_loginView == nil) {
        _loginView = [[UIView alloc]init];
        _loginView.backgroundColor = [UIColor whiteColor];
        _loginView.frame = CGRectMake(60, 60, kScreenWidth - 300-120, kScreenHeight - 49-64-120);
        _loginView.hidden = YES;
    }
    return _loginView;
}

- (UIButton *)loginBtn {
    if (_loginBtn == nil) {
        _loginBtn = [UIButton buttonWithType:0];
        _loginBtn.frame = CGRectMake((kScreenWidth - 300-120)/2-60, (kScreenHeight - 49-64-120)/2 - 30, 120, 60);
        _loginBtn.backgroundColor = [UIColor blueColor];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBtn.clipsToBounds = YES;
        _loginBtn.layer.cornerRadius = 4;
        [_loginBtn addTarget:self action:@selector(clcikLoginBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}
#pragma mark - 登陆
- (void)clcikLoginBtn {
    if ([self.HeadImgDetegate respondsToSelector:@selector(clickLogin)]){
        [self.HeadImgDetegate clickLogin];
    }
}

- (NSArray *)tagAry{
    if (_tagAry == nil) {
        _tagAry = @[@"姓名",@"年龄",@"简介",@"地区"];
    }
    return _tagAry;
}



- (void)configWithImgage:(NSString *)head{
    [self.headImg sd_setImageWithURL:[NSURL URLWithString:head] placeholderImage:[UIImage imageNamed:@"touxiang"]];
//    self.nameTF.placeholder = @"ADSL父控件爱上了";
}
- (NSDictionary *)dataDic {
    if (!_dataDic) {
        _dataDic = [NSDictionary dictionary];
    }
    return _dataDic;
}

- (void) configWithData:(NSDictionary *)dic {
    self.nameTF.text = nil;
    self.ageTF.text = nil;
    self.qainTF.text = nil;
    self.addressTF.text = nil;
    
    self.nameTF.placeholder = dic[@"nickname"];
    self.ageTF.placeholder = dic[@"age"];
    self.qainTF.placeholder = dic[@"sign"];
    
    self.userDic = dic;
    
    self.addressTF.placeholder = dic[@"city_id"];
    NSLog(@"============%@", dic);
    
    [self loadProData];
}
- (void) loadProData {
    NSString *getUrl = [NSString stringWithFormat:@"%@%@", [[VersionManager shareManager] currentVersion], kPRO];
    kDLog(@"获取省接口是：%@", getUrl);
    
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取省接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            for (NSDictionary *dic in proArray) {
                if ([dic[@"province_id"] isEqualToString:self.userDic[@"city_id"]]) {
                    self.proName = dic[@"name"];
                    
                    [self loadCityData];
                } else {
                    
                    self.addressTF.placeholder = @"请选择地区";
                }
            }
        }
        
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取省失败，错误是：%@", error);
    }];
}
- (void) loadCityData {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@province_id/%@", [[VersionManager shareManager] currentVersion], kCITY, self.userDic[@"city_id"]];
    kDLog(@"获取市接口是：%@", getUrl);
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取市接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            for (NSDictionary *dic in proArray) {
                if ([dic[@"city_id"] isEqualToString:self.userDic[@"city_id"]]) {
                    self.cityName = dic[@"name"];
                    [self loadCountyData];
                } else {
                    
                    self.addressTF.placeholder = [NSString stringWithFormat:@"%@", self.proName];
                }
            }
        }
        
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取市失败，错误是：%@", error);
    }];
}
- (void) loadCountyData {
    
    NSString *getUrl = [NSString stringWithFormat:@"%@%@city_id/%@", [[VersionManager shareManager] currentVersion], kAREA, self.userDic[@"district_id"]];
    kDLog(@"获取县接口是：%@", self.userDic[@""]);
    [CHNetWorkSingleton requestAFWithURL:getUrl params:nil httpMethod:@"GET" isHUD:NO finishBlock:^(id result) {
        
        NSLog(@"获取县接口返回的信息是：%@", result);
        NSArray *proArray = result[@"data"];
        NSString *code = result[@"code"];
        
        if ([code isEqualToString:@"11"] && proArray != nil) {
            
            for (NSDictionary *dic in proArray) {
                if ([dic[@"district_id"] isEqualToString:self.userDic[@"district_id"]]) {
                    self.countyName = dic[@"name"];
                    
                    [self configAddressTF];
                } else {
                    
                    self.addressTF.placeholder = [NSString stringWithFormat:@"%@%@", self.proName, self.cityName];
                }
            }
        }
        
        
    } errorBlock:^(NSError *error) {
        
        kDLog(@"获取县失败，错误是：%@", error);
    }];
}

- (void) configAddressTF {
    
    self.addressTF.placeholder = [NSString stringWithFormat:@"%@%@%@", self.proName, self.cityName, self.countyName];
}

- (void) hideAddressView {
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self.addressView.frame = CGRectMake(0, kScreenHeight, kScreenWidth, 500);
    } completion:^(BOOL finished) {
        
        [self.addressView removeFromSuperview];
    }];
}

@end
